package io.xiaojl.xj2ee.modules.sys.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.xiaojl.xj2ee.common.exception.XjeeException;
import io.xiaojl.xj2ee.common.kit.PageWrapper;
import io.xiaojl.xj2ee.modules.sys.entity.SysDeptEntity;
import io.xiaojl.xj2ee.modules.sys.entity.SysUserEntity;
import io.xiaojl.xj2ee.modules.sys.mapper.SysUserEntityMapper;
import io.xiaojl.xj2ee.modules.sys.service.SysUserService;


@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
	@Autowired
	private SysUserEntityMapper sysUserMapper;
	@Autowired
	private SysDeptServiceImpl sysDeptService;
	
    @Override
    public PageWrapper<SysUserEntity> queryPage(Map<String, Object> params) {
    	PageWrapper<SysUserEntity> pageWrapper = new PageWrapper<SysUserEntity>(params);
		PageHelper.startPage(pageWrapper.getCurrPage(), pageWrapper.getPageSize(), pageWrapper.getOrderBy());
		
		List<SysUserEntity> list = sysUserMapper.selectListByPage(pageWrapper.getCondition());
		for(SysUserEntity record: list){
			Long deptId = record.getDeptId();
			SysDeptEntity sysDeptEntity = sysDeptService.selectById(deptId);
			record.setDeptName(sysDeptEntity.getName());
		}
		PageInfo<SysUserEntity> page = new PageInfo<>(list);
		
		pageWrapper.setList(page.getList());
		pageWrapper.setTotalCount(Integer.parseInt(page.getTotal()+""));
		pageWrapper.setTotalPage(page.getPages());
        return pageWrapper;
    }

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return sysUserMapper.queryAllMenuId(userId);
	}

	@Override
	public void save(SysUserEntity user) {
		sysUserMapper.insert(user);
	}

	@Override
	public void update(SysUserEntity user) {
		sysUserMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity record = sysUserMapper.selectByPrimaryKey(userId);
		if(record!=null){
			if(password.equals(record.getPassword())){
				record.setPassword(newPassword);
				int result = sysUserMapper.updateByPrimaryKeySelective(record);
				if(result>0){
					return true;
				}
			}else{
				throw new XjeeException("更新用户密码：用户ID["+userId+"]原密码不正确");
			}
		}else{
			throw new XjeeException("更新用户密码：用户ID["+userId+"]不存在");
		}
		return false;
	}

	@Override
	public SysUserEntity selectById(Long userId) {
		return sysUserMapper.selectByPrimaryKey(userId);
	}

	@Override
	public int deleteBatchIds(Long[] userIds) {
		return sysUserMapper.deleteBatchIds(userIds);
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return sysUserMapper.queryAllPerms(userId);
	}

	@Override
	public SysUserEntity selectOne(SysUserEntity user) {
		return sysUserMapper.selectOne(user);
	}

}
